package com.fuint.utils.aliyun;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class LogisticsUtil {

    @Value("${aliyun.logistics.appcode}")
    private String appCode;
    @Value("${aliyun.logistics.appkey}")
    private String appKey;
    @Value("${aliyun.logistics.appsecret}")
    private String appSecret;
    @Value("${aliyun.logistics.host}")
    private String host;
    @Value("${aliyun.logistics.path}")
    private String path;

    public LogisticsData doPost(String expressNo, String mobile) {
        HttpEntity<MultiValueMap<String, String>> entity = getMultiValueMapHttpEntity(expressNo, mobile);

        RestTemplate restTemplate = new RestTemplate();
        try {
            String url = host + path;
            ResponseEntity<LogisticsResponse> response = restTemplate.exchange(url, HttpMethod.POST, entity, LogisticsResponse.class);
            LogisticsResponse body = response.getBody();

            if (Objects.isNull(body) || 200 != body.getCode()) {
                log.error("物流接口请求失败:" + JSONUtil.toJsonStr(response));
            }
            return body.getData();
        } catch (Exception e) {
            log.error("物流接口请求失败:" + JSONUtil.toJsonStr(e));
        }
        return null;
    }

    private HttpEntity<MultiValueMap<String, String>> getMultiValueMapHttpEntity(String expressNo, String mobile) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + appCode);
        // headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("expressNo", expressNo);
        formData.add("mobile", mobile);
        return new HttpEntity<>(formData, headers);
    }

}
